import Vue from 'vue';
import Axios from 'axios';
import Qs from 'qs';
import Store from '@/stores/index';
import { common } from '@/utils';

export default class Service {
  constructor() {
    this.vm = new Vue();

    this.instance = Axios.create({
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
      },
      timeout: 0,
      paramsSerializer: (params) => Qs.stringify(params, { indices: false }),
    });

    this.instance.interceptors.request.use(
      (config) => {
        config.baseURL = Store.state.common.baseUrl;

        if (config.isCheckToken) {
          if (Store.state.common.user.token) {
            config.headers.Authorization = `bearer ${Store.state.common.user.token}`;
          } else {
            const tips = '登录失效，请重新登录';
            common.checkToken.call(this.vm);
            Promise.reject(tips);
          }
        }

        return Promise.resolve(config);
      },
      (error) => Promise.reject(error),
    );

    this.instance.interceptors.response.use(
      (response) => {
        const { data } = response;
        return Promise.resolve(data);
      },
      (error) => {
        const code = parseInt(error?.response?.status, 10);
        const httpCode = {
          401: '登录失效，请重新登录',
          403: '服务器拒绝本次访问',
          404: '请求资源未找到',
          500: '内部服务器错误',
          501: '服务器不支持该请求中使用的方法',
          502: '网关错误',
          504: '网关超时',
        };

        if (code === 400 || code === 500) {
          const { message } = error?.response?.data?.errors[0];
          this.notify({ message });
        } else if (code === 401) {
          common.checkToken.call(this.vm);
        } else {
          this.notify({ message: httpCode[code] ?? '服务器异常' });
        }

        return Promise.reject(error);
      },
    );
  }

  notify({ message = '' } = {}) {
    return this.vm.$dialog.alert({
      message,
    });
  }
}
